import re, random

from django.contrib.auth.hashers import make_password
from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from home.models import UserInfo
from user.service import get_user_by_account


class UserModelSerializer(ModelSerializer):
    token = serializers.CharField(max_length=1024, read_only=True)
    sms_code = serializers.CharField(max_length=1024, write_only=True)


    class Meta:
        model = UserInfo
        fields = ('phone', 'password', 'username', 'id', 'token', 'sms_code')
        extra_kwargs = {
            "phone": {
                "write_only": True
            },
            "password": {
                "write_only": True
            },
            "id": {
                "read_only": True
            },
            "username": {
                "read_only": True
            },
        }

    def validate(self, attrs):
        phone = attrs.get('phone')
        password = attrs.get('password')
        sms_code = attrs.get('sms_code')

        if not re.match(r'^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$', phone):
            raise serializers.ValidationError('手机号格式不正确')
        # 密码包含数字, 英文, 字符中的两种以上，长度8-20
        if not re.match(r'^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,20}$', password):
            raise serializers.ValidationError('密码格式不正确,密码格式为包含数字, 英文, 字符中的两种以上，且长度为8-20')

        try:
            user = get_user_by_account(phone)
            print(892750, user)
        except UserInfo.DoesNotExist:
            user = None
        # print(892750,user)
        if user:
            raise serializers.ValidationError("手机号已注册")

        #  验证手机号对应的验证码是否正确
        # 限制总共可以验证多少次 3次
        redis_connection = get_redis_connection("sms_code")
        phone_code = redis_connection.mget("mobile_%s" % phone)[0].decode('utf-8')
        if sms_code != phone_code:
            raise serializers.ValidationError("验证码错误")

        # 成功验证码后需要及时删除验证码
        print(8927, attrs)
        return attrs

    def create(self, validated_data):
        phone = validated_data.get('phone')
        password = validated_data.get('password')
        hsah_password = make_password(password)

        # 随机生成名字
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
        name = ''.join(random.sample(alphabet, 5))

        user = UserInfo.objects.create(
            phone=phone,
            username=name,
            password=hsah_password,
            email=phone + '@136.com'
        )
        # 生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        return user






